<template>
    <div class="container">
        <div class="search-content">
            <el-form :model="searchContent" ref="searchFrom" :inline="true">
                <el-form-item label="日期：">
                    <el-date-picker
                        v-model="dateInterval"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        :picker-options="pickerOptions"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @change="handleChangeTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="商家名称：">
                    <el-select
                        v-model="searchContent.store_id"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        autocomplete
                        placeholder="选择店铺、搜索店铺"
                        :remote-method="handleRemote"
                        :loading="loading"
                        @focus="handleFocus">
                        <el-option
                            v-for="item in storeLists"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属品线：">
                    <el-select v-model="searchContent.depart_id" @change='handleDepartChange' placeholder="全部" clearable>
                        <el-option
                            v-for="item in departType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="total-desc">当前条件下去重客户总数为 <span>{{pageArr.numPep|_formatterNum}}</span> 人</div>
        <div class="search-list wechat-customers">
            <el-table 
                border 
                :data="dataList" 
                header-cell-class-name="hdCellStyle" 
                :default-sort="sort"
                @sort-change="handleSortChange"
            >
                <el-table-column 
                  type="index" 
                  label="序号"
                  width="100"
                  align="center"
                >
                </el-table-column>
                <el-table-column 
                  label="店铺名称"
                  min-width="180"
                  align="center"
                  prop="store_name"
                >
                </el-table-column>
                <el-table-column 
                  label="所属品线"
                  min-width="150"
                  align="center"
                  prop="depart_name"
                >
                </el-table-column>
                <el-table-column 
                  label="企微去重客户总数"
                  min-width="150"
                  align="center"
                  prop="count" 
                  sortable="custom"
                >
                </el-table-column>
            </el-table>
        </div>
        <div class="bottom flex-item">
            <div class="btn-group">
				<el-button type="primary" @click="getData('export')">导出</el-button>
            </div>
            <div class="paginationOne">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageArr.curpage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageArr.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageArr.total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
import { formatterNumber, dateFormatter } from "@/common/js/util.js";
import Qs from 'qs';
export default {
    data() {
        return {
            searchContent: {
                begin_date: '',       // 开始时间
                end_date: '',         // 结束时间 
                store_id: '',         // 店铺ID
                store_name: '',       // 店铺名称
                depart_id: '',        // 品线ID
                is_search: false      // 是否处于搜索
            },
            dateInterval: [],
            departType: [],            // 品线类型数组
            pickerMinDate: null,
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.pickerMinDate = minDate
                },
                disabledDate: time => {
                    const intervalTtime = 24 * 30 * 24 * 3600 * 1000; // 仅支持选择24个月范围
                    const currDate = this.pickerMinDate ? new Date(this.pickerMinDate) : new Date()
                    const minTime = currDate.getTime() - intervalTtime;
                    const maxTime = currDate.getTime() + intervalTtime;
                    let date = new Date(), dateTime = Date.now(), nowMonth = true;
                    // nowMonth = time.getFullYear() <= date.getFullYear() && time.getMonth() < date.getMonth(); // 不支持当月
                    dateTime -= 8.64e7; // 不支持当日
                    return time.getTime() > dateTime || time.getTime() < minTime || time.getTime() > maxTime || !nowMonth
                }
            },
            sort: {prop: 'count', order: 'descending'}, // 排序
            order: {
                descending: "desc",
                ascending: 'asc'
            },
            pageArr: {
                curpage: 1,            // 当前页码
                pageSize: localStorage.getItem('pageSize') * 1 || 10,         // 每页显示数量
                total: 0,              // 数据总数
                numPep: null              // 去重客户总数
            },
            dataList: [],              // 列表数据
            storeLists: [],            // 店铺数据
            loading: false,            // 是否处于远程加载店铺数据中
        }
    },
    filters: {
        _formatterNum(val) {
            if (val === null) return '***'
            return formatterNumber(val, 10000, 2, true)
        }
    },
    methods: {
        // 店铺表单获得焦点
        handleFocus(){
            // if(this.storeLists.length <= 0) {
                this.getStoreList();
            // }
        },
        // 店铺搜索
        handleRemote(keywords) {
            this.getStoreList(keywords);
        },
        // 获取店铺列表数据
        getStoreList(storeName = '', store_id_in = null) {
            this.loading = true
            const data = {
                page: 1,
                eachNum: 200,
                storeName,
                loadingclose: false,
                storeUserName: '',
                type: 'filter_not_yt'
            };
            if(store_id_in) {
                data.store_id_in = store_id_in
            }
            this.$http.post('/admin/store/index.php?act=storeManage&op=getStoreList', data).then(res => {
                this.loading = false
                if (res.code == 1) {
                    this.storeLists = res.data && res.data.list && 
                    res.data.list.map(item => ({
                        value: item.store_id,
                        label: item.store_name
                    })) || []
                } else {
                    this.storeLists = [];
                    res.msg && this.$message.error(res.msg)
                }
            })
        },
        // 获取品线数据
        getDepart() {
            this.$http.post("/admin/depart/index.php?act=departManage&op=groupList", {depart_id: 600}) // 600 为集团ID
            .then( res => {
                if (res.code == 1 && res.data.length > 0) {
                    this.departType = res.data.map(item =>({
                        depart_id: item.depart_id,
                        store_ids: item.store_ids,
                        label: item.depart_name, 
                        value: item.depart_id
                    }));
                } else {
                    this.$message.error("品线数据获取失败!");
                }
            })
        },
        handleChangeTime(val) {
            if(val) {
                this.searchContent.begin_date = val[0];
                this.searchContent.end_date = val[1];
            } else {
                this.searchContent.begin_date = null;
                this.searchContent.end_date = null;
            }
        },
        async getData(action = null) {
            let datas = {
                pageSize: this.pageArr.pageSize,
                page: this.pageArr.curpage,
                //sort: this.sort.prop, // 排序字段
                order: this.order[this.sort.order] // 排序规则
            }
            if(this.searchContent.is_search) {
                datas = {...datas, ...this.searchContent};
            }
            if(action == "export") {
                datas.is_export = 1;
                const origin = this.$store.state.location.origin;
				const url = origin + '/admin/store/index.php?act=followUser&op=wechatUserDetail&' + Qs.stringify(datas);
                window.open(url)
            } else {
                this.$http.get('/admin/store/index.php?act=followUser&op=wechatUserDetail', {params: datas}).then(res => {
                    if(res.code == 1) {
                        this.dataList = this.fieldFilter(res.data.list, [
                            "store_id", "depart_name", "store_name", "count"
                        ]);
                        this.pageArr.total = parseInt(res.data.totalCount)
                        this.pageArr.numPep = res.data.numPep
                    }
                })
            }
        },
        handleSizeChange(pageSize) {
            localStorage.setItem('pageSize', pageSize);
			this.pageArr.pageSize = pageSize;
			this.pageArr.curpage = 1
			this.getData();
        },
        handleCurrentChange(page) {
			this.pageArr.curpage = page;
			this.getData();
        },
        fieldFilter(data, field) {
            if(!data) return [];
            return data.map((item, key) => {
                let obj = {};
                field.map(item2 => {
                    if(item[item2]) {
                        obj[item2] = item[item2]
                    }
                })
                return obj;
            })
        },
        // 品线选择
        handleDepartChange(val) {
            const depart = this.departType.find(depart => depart.depart_id == val)
            // this.searchContent.store_id_in = depart.store_ids.join(",")
            // this.searchContent.store_id = ''
            // this.getStoreList('', this.searchContent.store_id_in)
        },
        handleSearch() {
            if(!this.searchContent.is_search) this.searchContent.is_search = true;
            this.pageArr.curpage = 1
            this.getData();
        },
        handleReset() {
            this.selectTime = null;
            this.$refs.searchFrom.resetFields();
            this.storeLists = []
            if(!this.searchContent.is_search) return;
            this.searchContent = {
                is_search: false
            }
            this.pageArr.curpage = 1
            this.dateInterval = []
            this.setDefaultDate()
            this.getData();
        },
        handleSortChange({ column, prop, order }) {
            this.sort.order = order
            this.pageArr.curpage = 1
            this.getData()
        },
        setDefaultDate() {
            const date = new Date()
            date.setDate(date.getDate() - 1)
            const end = dateFormatter("YYYY-MM-DD", date.getTime())
            // this.dateInterval = ['', end]
            this.searchContent.is_search = true
            this.searchContent.end_date = end
        }
    },
    created() {
        
        this.setDefaultDate()

        this.admin_is_super = this.$store.getters["user_info"].admin_is_super
        this.$parent.showButton = false;
        this.getDepart()
        this.getData()
    },
	mounted() {
		resize(this)
	}
}
</script>
<style lang="scss" scoped>
.container {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    display: -webkit-flex;
    justify-content: space-between;
    overflow: hidden;
    box-sizing: border-box;
    .search-content {
        padding-left: 0;
        margin-left: -10px;
    }
    .search-list {
        flex-grow: 1;
        height: 100px;
        /deep/.el-table {
            height: 100%;
            .el-table__body-wrapper, .el-table__fixed-body-wrapper {
                height: calc(100% - 36px)!important;
                overflow-y: auto;
            }
            &.el-table--mini th {
                padding: 4px 0;
            }
            .cell { line-height: 22px; }
            .caret-wrapper {
                height: 27px;
            }
            .sort-caret.ascending {
                top: 1px
            }
            .sort-caret.descending {
                bottom: 4px;
            }
            //滚动条的宽度
            .el-table__body-wrapper {
                &::-webkit-scrollbar { 
                    width: 7px;
                    height: 7px;
                }
                //滚动条的滑块
                &::-webkit-scrollbar-thumb {
                    cursor: pointer;
                    background-color: rgba(144, 147, 153, 0.3);
                    border-radius: 7px;
                }
            }
        }
    }
}
.total-desc { 
    font-weight: bold;
    margin: -12px 0 12px;
    font-size: 14px;
    span {
        color: #FF5A5A;
    }
}
.bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>